package common

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/silenceper/wechat/v2/cache"
	"github.com/silenceper/wechat/v2/credential"
	"github.com/silenceper/wechat/v2/miniprogram/qrcode"
	"github.com/silenceper/wechat/v2/miniprogram/urllink"
	"hotgo/internal/library/storager"
	"hotgo/internal/library/wechat"
	"hotgo/internal/model/input/apiin"

	"hotgo/api/api/common/v1"
)

func (c *ControllerV1) MiniProgramQrCode(ctx context.Context, req *v1.MiniProgramQrCodeReq) (res *v1.MiniProgramQrCodeRes, err error) {

	res = new(v1.MiniProgramQrCodeRes)
	res.MiniProgramQrCodeModel = new(apiin.MiniProgramQrCodeModel)

	// 获取小程序二维码
	miniProgram := wechat.NewMpPlatform(ctx)

	miniProgram.SetAccessTokenHandle(credential.NewDefaultAccessToken(
		wechat.GetConfig().OpenAppID, wechat.GetConfig().OpenAppSecret, credential.CacheKeyMiniProgramPrefix, cache.NewMemory()))

	envVersion := g.Cfg().MustGet(ctx, "system.envVersion", "trial").String()
	checkPath := gconv.PtrBool(false)
	if envVersion == "release" {
		checkPath = gconv.PtrBool(true)
	}
	qrCode, err := miniProgram.GetQRCode().GetWXACodeUnlimit(qrcode.QRCoder{
		Path:       req.Path,
		Page:       req.Path,
		Width:      req.Width,
		Scene:      req.Scene,
		IsHyaline:  req.IsHyaline,
		CheckPath:  checkPath,
		EnvVersion: g.Cfg().MustGet(ctx, "system.envVersion", "trial").String(),
	})
	if err != nil {
		return
	}

	drive := &storager.OssDrive{}
	fullPath, err := drive.UploadBytes(ctx, qrCode)
	if err != nil {
		return
	}

	res.QrCodeUrl = fullPath
	res.UrlLink, err = miniProgram.GetURLLink().Generate(&urllink.ULParams{
		Path:           req.Path,
		Query:          req.Scene,
		ExpireType:     1,
		ExpireInterval: 30,
		EnvVersion:     g.Cfg().MustGet(ctx, "system.envVersion", "trial").String(),
	})

	return
}
